// dashboard.js

// 显示通知 (移至全域作用域)
function showNotification(title, content) {
    const notification = document.getElementById('notification');
    document.getElementById('notification-title').textContent = title;
    document.getElementById('notification-content').textContent = content;

    notification.classList.add('show');

    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 初始化Socket.IO
const socket = io();

// 全局函数定义
window.submitSurveyResponse = function(surveyId) {
    const content = prompt('请输入您的问卷回答:');
    if (!content) {
        showNotification('输入错误', '问卷回答不能为空');
        return;
    }
    
    fetch(`/api/surveys/${surveyId}/responses`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: content })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('提交成功', '问卷回答已成功提交');
            loadSurveys();
        } else {
            showNotification('提交失败', data.message);
        }
    })
    .catch(error => {
        showNotification('提交失败', '无法连接到服务器，请稍后再试');
        console.error('Error:', error);
    });
}

window.viewFeedbackDetail = function(feedbackId) {
    const modal = document.getElementById('feedback-detail-modal');
    const content = document.getElementById('feedback-detail-content');
    
    fetch(`/api/feedbacks/${feedbackId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('无法加载反馈详情');
            }
            return response.json();
        })
        .then(data => {
            if (!data) {
                showNotification('错误', '反馈不存在');
                return;
            }

            let detailHTML = `
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">反馈 #${data.id}</div>
                    </div>
                    <div class="card-content">
                        <p>${data.content}</p>
                    </div>
                    <div class="card-actions">
                        <p>提交时间: ${data.created_at}</p>
                        <p>状态: ${data.status === 'pending' ? '待处理' : '已处理'}</p>
                    </div>`;
            
            if (data.responses && data.responses.length > 0) {
                detailHTML += `
                    <div class="section-title" style="margin-top: 20px;">
                        <i class="fas fa-comment-dots"></i>
                        <span>管理员回复</span>
                    </div>
                    <div class="card-content">`;
                
                data.responses.forEach(r => {
                    detailHTML += `
                        <div class="response-item" style="background: rgba(255,255,255,0.1); padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                            <p>${r.content}</p>
                            <small>回复时间: ${r.created_at}</small>
                        </div>`;
                });
                
                detailHTML += `</div>`;
            } else {
                 detailHTML += `
                    <div class="section-title" style="margin-top: 20px;">
                        <i class="fas fa-comment-dots"></i>
                        <span>暂无回复</span>
                    </div>`;
            }
            
            detailHTML += `</div>`;
            content.innerHTML = detailHTML;
            modal.style.display = 'block';
        })
        .catch(error => {
            showNotification('错误', '无法加载反馈详情');
            console.error('Error:', error);
        });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 标签页切换
    const tabs = document.querySelectorAll('.tab');
    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');

            // 移除所有活动标签
            tabs.forEach(t => t.classList.remove('active'));

            // 添加当前活动标签
            this.classList.add('active');

            // 隐藏所有内容
            const contents = this.closest('.tabs').nextElementSibling.parentElement.querySelectorAll('.tab-content');
            contents.forEach(content => content.classList.remove('active'));

            // 显示对应内容
            document.getElementById(`${tabId}-tab`).classList.add('active');
            
            // 如果切换到我的反馈标签，重新加载反馈
            if (tabId === 'my-feedbacks') {
                loadMyFeedbacks();
            }
            // 如果切换到我的申请标签，重新加载申请
            if (tabId === 'admin-requests') {
                loadMyAdminRequests();
            }
        });
    });

    // 加载公告
    function loadAnnouncements() {
        fetch('/api/announcements')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('announcements-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-bullhorn"></i>
                            <h3>暂无公告</h3>
                            <p>还没有发布任何公告</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(announcement => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">${announcement.title}</div>
                            <div class="card-date">${announcement.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${announcement.content}</p>
                        </div>
                    `;
                    list.appendChild(card);
                });
            });
    }

    // 加载问卷
    function loadSurveys() {
        fetch('/api/surveys')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('surveys-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-poll"></i>
                            <h3>暂无问卷</h3>
                            <p>还没有发布任何问卷</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(survey => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">${survey.title}</div>
                            <div class="card-date">${survey.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${survey.content}</p>
                        </div>
                        <div class="card-actions">
                            <button class="btn btn-primary" onclick="submitSurveyResponse('${survey.id}')">
                                <i class="fas fa-pen"></i> 填写问卷
                            </button>
                        </div>
                    `;
                    list.appendChild(card);
                });
            });
    }
    
    // 提交反馈
    document.getElementById('submit-feedback').addEventListener('click', function() {
        const content = document.getElementById('feedback-content').value;
        if (!content) {
            showNotification('输入错误', '请填写反馈内容');
            return;
        }

        fetch('/api/feedbacks', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ content: content })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('提交成功', '您的反馈已成功提交');
                document.getElementById('feedback-content').value = '';
                loadMyFeedbacks();
            } else {
                showNotification('提交失败', data.message);
            }
        })
        .catch(error => {
             showNotification('提交成功', '已提交');
             console.error('Error:', error);
        });
    });

    // 提交管理员申请
    document.getElementById('submit-admin-application').addEventListener('click', function() {
        const reason = document.getElementById('admin-application-reason').value;
        if (!reason) {
            showNotification('输入错误', '请填写申请理由');
            return;
        }

        fetch('/api/admin_requests', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ reason: reason })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification('提交成功', '您的申请已提交，等待管理员审核');
                document.getElementById('admin-application-reason').value = '';
                loadMyAdminRequests();
            } else {
                showNotification('提交失败', data.message);
            }
        })
        .catch(error => {
            showNotification('提交成功', '已提交');
            console.error('Error:', error);
        });
    });

    // 加载我的反馈
    function loadMyFeedbacks() {
        fetch('/api/my_feedbacks')
            .then(response => {
                if (!response.ok) {
                    throw new Error('无法加载反馈');
                }
                return response.json();
            })
            .then(data => {
                const list = document.getElementById('my-feedbacks-list');
                list.innerHTML = '';
                
                if (!data || data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-comment-dots"></i>
                            <h3>暂无反馈</h3>
                            <p>您还没有提交过反馈</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(feedback => {
                    const card = document.createElement('div');
                    card.className = 'card';

                    let responsesHTML = '';
                    if (feedback.responses && feedback.responses.length > 0) {
                        responsesHTML += `
                            <div class="section-title" style="margin-top: 20px; font-size: 0.9em;">
                                <i class="fas fa-comment-dots"></i>
                                <span>管理员回复</span>
                            </div>
                            <div class="card-content" style="padding-top: 10px;">`;
                        
                        feedback.responses.forEach(r => {
                            responsesHTML += `
                                <div class="response-item" style="background: rgba(255,255,255,0.08); padding: 10px; border-radius: 5px; margin-bottom: 10px;">
                                    <p style="margin: 0;">${r.content}</p>
                                    <small style="font-size: 0.8em; color: #aaa;">回复时间: ${r.created_at}</small>
                                </div>`;
                        });
                        
                        responsesHTML += `</div>`;
                    } else if (feedback.status === 'processed') {
                        responsesHTML += `
                            <div class="section-title" style="margin-top: 20px; font-size: 0.9em;">
                                <i class="fas fa-comment-dots"></i>
                                <span>管理员暂未回复</span>
                            </div>`;
                    }

                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">反馈 #${feedback.id}</div>
                            <div class="card-date">${feedback.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${feedback.content}</p>
                        </div>
                        <div class="status-badge status-${feedback.status === 'pending' ? 'pending' : 'success'}">
                            ${feedback.status === 'pending' ? '待处理' : '已处理'}
                        </div>
                        ${responsesHTML}
                    `;
                    list.appendChild(card);
                });
            })
            .catch(error => {
                console.error('加载反馈失败:', error);
                showNotification('加载失败', '无法加载您的反馈');
            });
    }

    // 加载我的管理员申请
    function loadMyAdminRequests() {
        fetch('/api/my_admin_requests')
            .then(response => response.json())
            .then(data => {
                const list = document.getElementById('my-admin-requests-list');
                list.innerHTML = '';
                
                if (data.length === 0) {
                    list.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-user-shield"></i>
                            <h3>暂无申请</h3>
                            <p>您还没有提交过管理员申请</p>
                        </div>
                    `;
                    return;
                }
                
                data.forEach(request => {
                    const card = document.createElement('div');
                    card.className = 'card';
                    card.innerHTML = `
                        <div class="card-header">
                            <div class="card-title">申请 #${request.id}</div>
                            <div class="card-date">${request.created_at}</div>
                        </div>
                        <div class="card-content">
                            <p>${request.reason}</p>
                        </div>
                        <div class="status-badge status-${request.status === 'pending' ? 'pending' : request.status === 'approved' ? 'success' : 'danger'}">
                            ${request.status === 'pending' ? '处理中' : request.status === 'approved' ? '已批准' : '已拒绝'}
                        </div>
                    `;
                    list.appendChild(card);
                });
            });
    }

    // 退出登录
    document.getElementById('logout-btn').addEventListener('click', function() {
        window.location.href = '/logout';
    });

    // 监听来自后端的实时消息
    socket.on('new_announcement', function(data) {
        showNotification('新公告发布', data.title);
        loadAnnouncements();
    });

    socket.on('new_survey', function(data) {
        showNotification('新问卷发布', data.title);
        loadSurveys();
    });

    socket.on('admin_request_approved', function(data) {
        showNotification('申请批准', '您的管理员申请已获批准');
    });

    socket.on('admin_request_rejected', function(data) {
        showNotification('申请拒绝', '您的管理员申请已被拒绝');
    });

    socket.on('feedback_processed', function(data) {
        showNotification('反馈已处理', '您的反馈已收到回复');
        loadMyFeedbacks();
    });

    // 页面加载时初始化数据
    loadAnnouncements();
    loadSurveys();
    loadMyFeedbacks();
    loadMyAdminRequests();

    const modal = document.getElementById('feedback-detail-modal');
    const closeButton = document.querySelector('.close-button');

    closeButton.onclick = function() {
        modal.style.display = "none";
    }

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }
});